//
//  ConQrCodeScannerController.m
//  Shengzhuli
//
//  Created by FXGuo on 17/3/22.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConQrCodeScannerController.h"
#import <AVFoundation/AVFoundation.h>
#import "UIAlertView+Entension.h"
#import "PersonNetWork.h"
#import "SZLAccountHelper.h"
#import "MBProgressHUD+MJ.h"
#import "ConEditCardViewController.h"
#import "NSString+Valid.h"
#import "UIAlertView+Entension.h"

@interface ConQrCodeScannerController ()<AVCaptureMetadataOutputObjectsDelegate,CAAnimationDelegate>

@property (nonatomic,strong) AVCaptureSession *session;
@property (nonatomic,strong) AVCaptureDevice *device;
@property (nonatomic,strong) AVCaptureDeviceInput *input;
@property (nonatomic,strong) AVCaptureMetadataOutput *output;
@property (nonatomic,strong) AVCaptureVideoPreviewLayer *layer;

@property (nonatomic,weak) UIImageView *rectView;
@property (nonatomic,weak) UIImageView *lineView;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,strong) NSString *friendsPhone;

@end

@implementation ConQrCodeScannerController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    self.navigationItem.title = @"二维码扫描";
    [self setUpScanner];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.session startRunning];
}
- (void)addQrRect
{
    UIImageView *rectView = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenW-200)/2.0, (ScreenH-300)/2.0, 200, 200)];
    rectView.backgroundColor = [UIColor clearColor];
    rectView.image = [UIImage imageNamed:@"扫描框"];
    self.rectView = rectView;
    [self.view addSubview:rectView];
    UIImageView *lineView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 0, 180, 5)];
    lineView.image = [UIImage imageNamed:@"扫描线"];
    self.lineView = lineView;
    [rectView addSubview:lineView];
    [self doLineAnimation];
}
- (void)setUpScanner
{
    [self.session addInput:self.input];
    [self.session addOutput:self.output];
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [self.output setMetadataObjectTypes:@[AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeQRCode]];
    [self.view.layer addSublayer:self.layer];
    [self addQrRect];
}
- (void)doLineAnimation
{
    NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(changeFrame) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
    self.timer = timer;
}
- (void)changeFrame
{
    CABasicAnimation *animation = [ConQrCodeScannerController moveYTime:1 fromY:[NSNumber numberWithFloat:5] toY:[NSNumber numberWithFloat:190] rep:OPEN_MAX];
    [self.lineView.layer addAnimation:animation forKey:@"LineAnimation"];
}
- (void)stopScanner
{
    [self.session stopRunning];
    [self.layer removeFromSuperlayer];
    [self.rectView removeFromSuperview];
    [self removeAnimation];
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
        NSLog(@"%@", object.stringValue);//扫描结果
        [self.session stopRunning];
        __WEAK
        if ([object.stringValue containsString:@"https://"]||[object.stringValue containsString:@"http://"]) {
            [self getCardInfoWithStr:object.stringValue];//请求
        }else {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"扫描结果" message:object.stringValue delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert handlerClickedButton:^(UIAlertView *alertView, NSInteger btnIndex) {
                [weakSelf.session startRunning];
            }];
        }
    } else {
        NSLog(@"没有扫描到数据");
    }
}
- (AVCaptureSession *)session
{
    if (!_session) {
        _session = [[AVCaptureSession alloc] init];
    }
    return _session;
}
- (AVCaptureDevice *)device
{
    if (!_device) {
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _device;
}

- (AVCaptureDeviceInput *)input
{
    if (!_input) {
        _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    }
    return _input;
}
- (AVCaptureMetadataOutput *)output
{
    if (!_output) {
        _output = [[AVCaptureMetadataOutput alloc] init];
        _output.rectOfInterest = CGRectMake((ScreenH-300)/2.0/ScreenH,(ScreenW-200)/2.0/ScreenW, 200/ScreenH, 200/ScreenW);
    }
    return _output;
}
- (AVCaptureVideoPreviewLayer *)layer
{
    if (!_layer) {
        _layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
        _layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _layer.frame = self.view.bounds;
    }
    return _layer;
}
+ (CABasicAnimation *)moveYTime:(float)time fromY:(NSNumber *)fromY toY:(NSNumber *)toY rep:(int)rep
{
    CABasicAnimation *animationMove = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    [animationMove setFromValue:fromY];
    [animationMove setToValue:toY];
    animationMove.duration = time;
    animationMove.repeatCount  = rep;
    animationMove.fillMode = kCAFillModeForwards;
    animationMove.removedOnCompletion = NO;
    animationMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    return animationMove;
}

- (void)removeAnimation
{
    [self.lineView.layer removeAnimationForKey:@"LineAnimation"];
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)getCardInfoWithStr:(NSString *)str
{
    NSArray *arr = [str componentsSeparatedByString:@"="];
    __WEAK
    if (arr.count <2) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"扫描结果" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert handlerClickedButton:^(UIAlertView *alertView, NSInteger btnIndex) {
            [weakSelf.session startRunning];
        }];
        return;
    }
    self.friendsPhone = arr[1];
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"mobilePhone"] = arr[1];//friendMobilePhone
    [self showClearBgWaiter];
    [PersonNetWork getSaoCardInfoWithParame:parame response:^(BOOL success, NSString *msg, CardInfoModel *info) {
        [self hideWaiter];
        if (success) {
            ConEditCardViewController *editVc = [[ConEditCardViewController alloc]init];
            editVc.type = EditTypeAddFriends;
            editVc.info = info;
            editVc.friendsPhone = self.friendsPhone;
            [weakSelf.navigationController pushViewController:editVc animated:YES];
        }else{
            [MBProgressHUD showError:msg];
            [self.session startRunning];
        }
    }];
}

@end
